package IconUrl

import (
	"FromNowOnPromote/博客系统/Tblog/controllers"
	"FromNowOnPromote/博客系统/Tblog/models"
	"FromNowOnPromote/博客系统/Tblog/models/User"
	"FromNowOnPromote/博客系统/Tblog/redis"
	"fmt"
	"io/ioutil"
	"os"
	"strconv"
	"time"
)

type IconUrl struct {
	controllers.MainController
}

//获取用户头像
func (this *IconUrl) Get() {
	id, err := this.GetInt64("v")
	if err != nil {
		fmt.Println(1)
		return
	}
	pic := fmt.Sprintf("static/img/avatar/%d.jpg", id)
	p, err1 := os.Open(pic)
	defer p.Close()
	if err1 != nil {
		fmt.Println(1)
		//用户为初始用户，为其设置一个初始图片
		pic = "static/img/avatar/logo2.png"
		p, _ = os.Open(pic)
		b, err2 := ioutil.ReadAll(p)
		if err2 != nil {
			fmt.Println(3)
			return
		}
		this.Ctx.Output.Body(b)
		return
	}
	b, err := ioutil.ReadAll(p)
	if err != nil {
		fmt.Println(4)
		return
	}
	this.Ctx.Output.Body(b)
	return
}

//上传用户头像
func (this *IconUrl) Post() {
	token := this.Ctx.GetCookie("uuid")
	rd := redis.R.Conn
	defer rd.Close()
	id, err1 := rd.Get(token)
	if err1 != nil {
		body := map[string]interface{}{"code": 300, "msg": "接口请求异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	f, _, err2 := this.GetFile("file")
	if err2 != nil {
		body := map[string]interface{}{"code": 301, "msg": "接口请求异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	defer f.Close()
	t := time.Now().Unix()
	userfile := fmt.Sprintf("%d.jpg", t)
	err3 := this.SaveToFile("file", "static/img/avatar/"+userfile)
	if err3 != nil {
		body := map[string]interface{}{"code": 302, "msg": "接口请求异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	//更新数据库
	user := User.TbUser{}
	db := models.ConnDb()
	model := db.Model(&user)
	defer db.Close()
	uuid, _ := strconv.Atoi(id)
	Icon := fmt.Sprintf("http://127.0.0.1:5000/user/icon/?v=%d", t)
	err4 := model.Where("Uuid=?", uuid).Update("IconUrl", Icon).Error
	if err4 != nil {
		body := map[string]interface{}{"code": 303, "msg": "接口请求异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	body := map[string]interface{}{"code": 200, "msg": "上传成功", "url": Icon}
	this.Data["json"] = body
	this.ServeJSON()
	return

}
